<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;

use Stbz\Api\SupplyClient;
use think\Db;
use think\db\Query;
use think\Exception;
use WeixinPay\WeixinPay;
use think\Config;
class Order
{
    private $appKey   = 'A855F0BA1EBCD119BEFBDE6EC07ECE65';
    private $appSecret = '68B892679EB78F9FB45ED3D62DE838B7';

    public function __construct()
    {
        vendor("JuHe.autoload");
    }
    /**
     * 创建订单
     */
    public function createOrder($input){

        $pay_method=$input['pay_method'];
        $pay_method_arr=explode(",",$pay_method);
        $tm=time();
        $spec_id=$input['spec_id'];
        $goods_id=$input['goods_id'];
        $order_sn=date("Y").date("m").mt_rand(1,9).date("d").mt_rand(1,9).date("Hi").mt_rand(1000,9999);

        $activity_invest=0;
        $direct_push=0;
        $inter_push=0;
        $activity_buyer=0;
        $activity_company=0;
        $activity_plateform=0;

        if(in_array($input['source_type'],[2,3])){ //供应链
            //库存判断
            //判断商品状态
            $goodsInfo=Db::name("choice_goods")->where(['goods_id'=>$input['goods_id']])->find();
            $status=$goodsInfo['status'];
            $supply_delete_status=$goodsInfo['supply_delete_status'];
            $shop_status =$goodsInfo['shop_status'];
            $shop_delete_status =$goodsInfo['shop_delete_status'];

            if(empty($status)||$shop_status==2){
                returnJson(-2003,'商品已下架');
            }
            if(empty($supply_delete_status)||empty($shop_delete_status)){
                returnJson(-2003,'商品已删除');
            }
            if(empty($goodsInfo['is_free_shipping'])){//不包邮
                $d_method=1;
            }
            //判断当前用户是否添加收货地址
            $address=Db::name("member_address")
                ->where(["member_id"=>$input['member_id'],"ma_id"=>$input['ma_id']])
                ->field("m_name,m_mobile,address_detail,location_area,province,city,county")
                ->find();

            if(empty($address)){
                returnJson(-2003,'请选择收货地址');
            }
            if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['province'])||empty($address['city'])||empty($address['county'])||empty($address['address_detail'])){
                returnJson(-2003,'收货地址信息不完整');
            }
            //获取商品规格信息
            $spec=$this->getGoodsSpec($goods_id,$spec_id,$goodsInfo);
            $stock=$spec['stock'];
            if($input['goods_num']>$stock){
                returnJson(-2003,"库存不足");
            }

            $gold_coin_num=0;
            $gold_coin=0;
            $price=$spec['agreement_price'];

            #处理价格数据
            $orderPrice=$this->computePrice($input['goods_id'],$input['source_type'],$spec['agreement_price']);
            extract($orderPrice);

            $goods=[];
            $goodsSpec=[];
            $goodsSpec['name']=$spec['spec_value_names'];
            $goodsSpec['g_name']=$goodsInfo['title'];

            //$goods['store_id']=$goodsInfo['source'];
            $goods['store_id']=0;
            $goodsSpec['gold_coin_num']=$gold_coin_num;
            $goodsSpec['cover_pic']=!empty($spec['image'])?$spec['image']:$goodsInfo['cover'];
            $goodsSpec['price']= $price;
            $goodsSpec['coin_price']=$gold_coin;
            $goodsSpec['goods_id']=$input['goods_id'];
            $goodsInfo['delivery_type']=2;
            $goodsSpec['proportion']=0;
            $goodsSpec['gold_coin_num']=0;
            $goodsSpec['copper_pop']=0;
            $goodsSpec['silver_pop']=0;
            $goodsSpec['gold_pop']=0;

            $province = $address['province'];
            $city = $address['city'];
            $area = $address['county'];
            $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
            $orderParam =[
                'address'=>[
                    'consignee' => $address['m_name'],
                    'phone' => $address['m_mobile'],
                    'province' => $province,
                    'city' => $city,
                    'area' => $area,
                    'street' => $street,
                    'description' => $street,
                ],
            ];
            //可售检测
            $this->availableCheck($goodsInfo['title'],$spec['spec_value_names'],$input['spec_id'],$input['goods_num'],$order_sn,$orderParam);



        }else{
            //获取商品主要信息
            $goods=Db::name("goods")
                ->where(['goods_id'=>$input["goods_id"],'store_id'=>$input['store_id']])
                ->field("g_name,g_type,member_id,goods_id,store_id,source_type,is_delete,
                limit_number,limit_start_time,limit_end_time,limit_num_status,limit_time_status,status")
                ->find();

            if(empty($goods['goods_id'])||$goods['is_delete']==2){
                returnJson(-2003,'当前商品不存在或已删除');
            }
            if($goods['status']!=1){
                returnJson(-2003,'当前商品未上架');
            }


            //判断是否为商家自己的商品
            if($goods['member_id']==$input["member_id"]){
                returnJson(-2003,'当前商品为当前用户商家商品');
            }

            //判断商品是否限购
            if($goods['limit_num_status']==2){//限购
                $limit_number=$goods['limit_number'];
                //规格ID
                $buyNums=Db::name("order_goods")->alias("og")
                    ->join("mm_order o","og.order_id=o.order_id")
                    ->where(['o.pay_status'=>2,"og.goods_id"=>$input["goods_id"],"o.member_id"=>$input["member_id"]])
                    ->value("og.goods_num");
                if($buyNums>=$limit_number){
                    returnJson(-2003,"当前商品限购".$limit_number);
                }
            }
            //判断活动是否限时
            if($goods['limit_time_status']==2){//限时
                if($tm<$goods['limit_start_time']){
                    returnJson(-2003,'当前商品活动还未开始');
                }

                if($tm>$goods['limit_end_time']){
                    returnJson(-2003,'当前商品活动已经过期');
                }
            }
            //判断是否选中配送方式
            $goodsInfo=Db::name("goods_info")
                ->where(['goods_id'=>$input["goods_id"]])
                ->field("inter_push,direct_push,distribution_method,delivery_type,delivery_fee")
                ->find();
            $distribution_method=$goodsInfo['distribution_method'];
            $d_method=0;
            if($distribution_method>0){
                $d_method=$input['d_method'];
                if(empty($d_method)){
                    returnJson(-2003,'请选中配送方式');
                }
                if(!in_array($d_method,array(1,2))){
                    returnJson(-2003,'商品不支持当前配送方式');
                }

            }
            //获取商品规格及相关信息
            $goods_spec=Db::name("goods_spec")
                ->where(['goods_id'=>$input['goods_id'],'gs_id'=>$spec_id])
                ->field("name,num,price,coin_price")
                ->find();

            if($goods_spec['num']<$input['goods_num']&&!in_array($goods['g_type'],[4,5])){

                returnJson(-2003,'当前规格商品库存不足');
            }
            if($d_method>0){
                //判断当前用户是否添加收货地址
                $address=Db::name("member_address")
                    ->where(["member_id"=>$input['member_id'],"ma_id"=>$input['ma_id']])
                    ->field("m_name,m_mobile,address_detail,location_area,province,city,county")
                    ->find();

                if(empty($address)){
                    returnJson(-2003,'请选择收货地址');
                }
                if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['location_area'])||empty($address['address_detail'])){
                    returnJson(-2003,'收货地址信息不完整');
                }
            }
            //获取商品规格信息
            $goodsSpec=Db::name("goods_spec")->alias("a")
                ->join("mm_goods g","g.goods_id=a.goods_id")
                ->join("mm_goods_info gn","g.goods_id=gn.goods_id")
                ->field("a.gs_id,a.gold_coin_num,a.proportion,a.name,a.price,a.coin_price,g.cover_pic,
                g.goods_id,g.g_name,gn.copper_pop,gn.gold_pop,gn.silver_pop")
                ->where(['a.gs_id'=>$spec_id])
                ->find();
            //1=消费爆品，2=裂变爆品,3=返利，4=活动,5=讲坛',
            //获取分销比例
            $setInfo = Db::name("system_config")
                ->where(['field_name' => "points_award_config"])
                ->value("field_value");
            $points_award_config = json_decode($setInfo, true);
            $buyer_rate = $points_award_config['buyer'];
            $invest_rate = $points_award_config['invest'];
            $direct_push_rate = $points_award_config['direct_push'];
            $inter_push_rate = $points_award_config['inter_push'];
            $platform_rate = $points_award_config['platform'];
            $city_company_rate = $points_award_config['city_company'];
            if(in_array($goods['g_type'],[3,5])){//返利 讲坛
                if($input['source_type']==4&&$goods['g_type']==3){//干货分享
                    $setInfo = Db::name("system_config")
                        ->where(['field_name' => "goods_share"])
                        ->value("field_value");
                    $points_award_config = json_decode($setInfo, true);
                    $orderAmount = $goodsSpec['price'];
                    $proportion =  $points_award_config['proportion'];
                    $distributionScore = $orderAmount * $proportion / 100;
                    if ( $distributionScore > 0) {
                        $buyer_score = $distributionScore * 20 / 100;
                        $activity_buyer=sprintf("%.2f",substr(sprintf("%.3f", $buyer_score), 0, -2));
                        //直推
                        $direct_push_score = $distributionScore * 5 / 100;
                        $direct_push=sprintf("%.2f",substr(sprintf("%.3f", $direct_push_score), 0, -2));
                        //间推
                        $inter_push_score = $distributionScore * 5 / 100;
                        $inter_push=sprintf("%.2f",substr(sprintf("%.3f", $inter_push_score), 0, -2));
                        $activity_invest=0;
                        //子公司
                        $activity_company=0;
                        //平台
                        $activity_plateform=0;
                    }else{
                        $activity_invest=0;
                        $direct_push=0;
                        $inter_push=0;
                        $activity_buyer=0;
                        $activity_company=0;
                        $activity_plateform=0;
                    }
                }else{
                    //订单总金额（不包括运费）
                    $orderAmount = $goodsSpec['price'];
                    $proportion = $goodsSpec['proportion'];
                    $distributionScore = $orderAmount * $proportion / 100;
                    if ( $distributionScore > 0) {
                        $buyer_score = $distributionScore * $buyer_rate / 100;
                        $activity_buyer=sprintf("%.2f",substr(sprintf("%.3f", $buyer_score), 0, -2));
                        //直推
                        $direct_push_score = $distributionScore * $direct_push_rate / 100;
                        $direct_push=sprintf("%.2f",substr(sprintf("%.3f", $direct_push_score), 0, -2));
                        //间推
                        $inter_push_score = $distributionScore * $inter_push_rate / 100;
                        $inter_push=sprintf("%.2f",substr(sprintf("%.3f", $inter_push_score), 0, -2));
                        //招商
                        $activity_invest=$distributionScore * $invest_rate / 100;
                        $activity_invest=sprintf("%.2f",substr(sprintf("%.3f",  $activity_invest), 0, -2));

                        //子公司
                        $activity_company=$distributionScore * $city_company_rate / 100;
                        $activity_company=sprintf("%.2f",substr(sprintf("%.3f",$activity_company), 0, -2));
                        //平台
                        $activity_plateform=$distributionScore * $platform_rate / 100;
                        $activity_plateform=sprintf("%.2f",substr(sprintf("%.3f",  $activity_plateform), 0, -2));
                    }else{
                        $activity_invest=0;
                        $direct_push=0;
                        $inter_push=0;
                        $activity_buyer=0;
                        $activity_company=0;
                        $activity_plateform=0;
                    }
                }

            }elseif($goods['g_type']==4){//限时特惠
                $direct_push=$goodsInfo['direct_push'];
                $inter_push=$goodsInfo['inter_push'];
                $activity_buyer=0;
                $activity_company=0;
                $activity_plateform=0;
                $activity_invest=0;
            }elseif($goods['g_type']==6){
                $direct_push=0;
                $inter_push=0;
                $activity_buyer=0;
                $activity_company=0;
                $activity_plateform=0;
                $activity_invest=0;
            }else{
                $activity_invest=0;
                $direct_push=0;
                $inter_push=0;
                $activity_buyer=0;
                $activity_company=0;
                $activity_plateform=0;
            }
        }
        $delivery_fee=0.00;
        if( $d_method>0){
            if(in_array($input['source_type'],[2,3])){
                $county=$address['county'];
                if(!empty($province)&&!empty( $city)&&!empty($county)&&!empty($address['address_detail'])){
                    $rst=$this->computeFee($input['spec_id'],$input['goods_num'],$orderParam);
                    $delivery_fee=$rst['freight'];
                }
                $d_method=1;
            }else{
                if($d_method==1){//送货上门
                    if($goodsInfo['delivery_type']==1){//自己配送
                        $delivery_fee=Db::name("store_detail")->where(['sa_id'=>$goods['store_id']])->value("delivery_fee");;
                    }elseif($goodsInfo['delivery_type']==2){//第三方配送

                    }
                }
            }

        }
        $orderGoods=[];
        //订单商品信息
        $orderGoods["goods_num"]=$input['goods_num'];
        $orderGoods["score_money"]= $goodsSpec['price'];
        $orderGoods["spec_pic"]= $goodsSpec['cover_pic'];
        $orderGoods["coin_money"]= $goodsSpec['coin_price'];
        $orderGoods["spec_name"]= $goodsSpec['name'];
        $orderGoods["goods_id"]= $goodsSpec['goods_id'];
        $orderGoods["goods_name"]= $goodsSpec['g_name'];
        $orderGoods["d_method"]=$d_method;
        $orderGoods["delivery_fee"]=$delivery_fee;
        $orderGoods["delivery_type"]=$goodsInfo['delivery_type'];
        $orderGoods["og_d_status"]=1;
        $orderGoods["create_time"]= $tm;
        $orderGoods["update_time"]= $tm;
        $orderGoods["spec_id"]=$spec_id;
        //分销
        $orderGoods["proportion"]=$goodsSpec['proportion'];
        $orderGoods["give_coin"]=$goodsSpec['gold_coin_num'];
        $orderGoods["copper"]=$goodsSpec['copper_pop'];
        $orderGoods["silver"]=$goodsSpec['silver_pop'];
        $orderGoods["golden"]=$goodsSpec['gold_pop'];
        $orderGoods["activity_direct_push"]=$direct_push;
        $orderGoods["activity_inter_push"]=$inter_push;
        $orderGoods['activity_buyer']=$activity_buyer;
        $orderGoods['activity_company']=$activity_company;
        $orderGoods['activity_plateform']=$activity_plateform;
        $orderGoods['activity_invest']=$activity_invest;
        //订单信息
        $orderData=[];
        $orderData['ma_id']=$input['ma_id'];
        $orderData['source_type']=$input['source_type'];
        $orderData['order_sn']=$order_sn;
        $orderData['status']=1;
        $orderData['pay_status']=1;
        $orderData['goods_class']=1;
        $orderData['member_id']=$input['member_id'];
        $orderData['store_id']=$input['store_id'];
        $orderData['order_score_money']= $goodsSpec['price']*$input['goods_num'];
        $orderData['order_coin_money']=$goodsSpec['coin_price']*$input['goods_num'];
        $orderData['order_delivery_fee']=$delivery_fee;
        if(!empty($address)){
            $orderData['receiver']=$address['m_name'];
            $orderData['re_phone']=$address['m_mobile'];
            $orderData['address']=$address['location_area'].$address['address_detail'];
        }
        $orderData['create_time']=$tm;
        $orderData['update_time']=$tm;
        $orderData['is_del']=1;
        //获取用户资产
        $coin_money=0;
        $score_money=0;
        $wx_money=0;
        $memberAsset=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->field("score,coin")->find();

        if($goodsSpec['coin_price']==0){//积分或现金支付
            $orderAmount=$goodsSpec['price']*$input['goods_num']+$delivery_fee;
            if(in_array(1,$pay_method_arr)) {//积分支付
                if($memberAsset['score']>$orderAmount){
                    $score_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $score_money=$memberAsset['score'];
                    $wx_money=$orderAmount-$memberAsset['score'];
                }
            }else{
                 $wx_money= $orderAmount;
            }
        }
        else{//积分+现金支付+金币
            if(in_array(1,$pay_method_arr)&&in_array(2,$pay_method_arr)){//积分+金币+微信支付
                 if($memberAsset['coin']>$goodsSpec['coin_price']*$input['goods_num']){//用户金币足够
                     $coin_money=$goodsSpec['coin_price']*$input['goods_num'];
                     $orderAmount=$goodsSpec['price']*$input['goods_num']+$delivery_fee;
                     if($memberAsset['score']>$orderAmount){
                         $score_money=$orderAmount-0.01;
                         $wx_money='0.01';
                     }else{
                         $score_money=$memberAsset['score'];
                         $wx_money=$orderAmount-$memberAsset['score'];
                     }
                 }else{
                     $coin_money=$memberAsset['coin'];
                     $orderAmount=$goodsSpec['coin_price']*$input['goods_num']+$goodsSpec['price']*$input['goods_num']+$delivery_fee-$coin_money;
                     if($memberAsset['score']>$orderAmount){
                         $score_money=$orderAmount-0.01;
                         $wx_money='0.01';
                     }else{
                         $score_money=$memberAsset['score'];
                         $wx_money=$orderAmount-$memberAsset['score'];
                     }
                 }
            }elseif(in_array(1,$pay_method_arr)){//积分支付
                $orderAmount=$goodsSpec['price']*$input['goods_num']+$delivery_fee+$goodsSpec['coin_price']*$input['goods_num'];
                if($memberAsset['score']>$orderAmount){
                    $score_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $score_money=$memberAsset['score'];
                    $wx_money=$orderAmount-$memberAsset['score'];
                }

            }elseif(in_array(2,$pay_method_arr)){//金币+现金支付
                $orderAmount=$goodsSpec['price']*$input['goods_num']+$delivery_fee+$goodsSpec['coin_price']*$input['goods_num'];
                if($memberAsset['coin']>$orderAmount){
                    $coin_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $coin_money=$memberAsset['coin'];
                    $wx_money=$orderAmount-$memberAsset['coin'];
                }

            }else{
                $wx_money=$goodsSpec['price']*$input['goods_num']+$delivery_fee+$goodsSpec['coin_price']*$input['goods_num'];
            }


        }


        if(($goodsSpec['price']*$input['goods_num']+$goodsSpec['coin_price']*$input['goods_num']+$delivery_fee)!=($coin_money+$score_money+$wx_money)){
            returnJson(-2004,'订单金额计算失败');
        }else{
            $orderData['wx_money']=$wx_money;
            $orderData['score_money']=$score_money;
            $orderData['coin_money']=$coin_money;
        }

        Db::startTrans();
        try{

            $orderID=Db::name("order")->insertGetId($orderData);
            if($orderID<=0){
                throw new Exception("更新失败5");
            }

            $orderGoods["order_id"]=$orderID;
            if($score_money>0){//写入积分冻结记录
              $num=Db::name("member_asset_log")
                  ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$score_money,
                      'source_type'=>2,'description'=>'商城待支付','change_type'=>1,'log_type_id'=>53,
                  'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败4");
                }
            }
            if($coin_money>0){//写入金币冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$coin_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>2,'log_type_id'=>54,
                        'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败3");
                }
            }
            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score-$score_money,frozen_score=frozen_score+$score_money,pay_frozen_score=pay_frozen_score+$score_money,coin=coin-$coin_money,frozen_coin=frozen_coin+$coin_money where member_id=".$input['member_id']." and score>=$score_money and coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败2");
                }
            }
            $num=Db::name("order_goods")->insert($orderGoods);
            if($num<=0){
                throw new Exception("更新失败1");
            }

            $result=$this->orderPay($order_sn,$input['member_id']);
            Db::commit();
            returnJson(200,'订单创建成功',$result);
        }catch (Exception $e){
            Db::rollback();
            returnJson(-2004,$e->getMessage());
        }
    }

    /**
     * 创建购物车订单
     */
    public function createCartOrder($input)
    {

        $member_id=$input['member_id'];
        $cart_list=$input['cart_list'];
        $store_id=$input['store_id'];

//        $cart_list=[
//            ['goods_id'=>23,'spec_id'=>48,'goods_num'=>1,'d_method'=>1],
//            ['goods_id'=>24,'spec_id'=>49,'goods_num'=>1,'d_method'=>1],
//        ];
        $cart_list=json_decode($cart_list,true);
        $tm=time();
        $order_sn=date("Y").date("m").mt_rand(1,9).date("d").mt_rand(1,9).date("Hi").mt_rand(1000,9999);
        $class_num=0;

        $direct_push=0;
        $inter_push=0;
        $activity_buyer=0;
        $activity_company=0;
        $activity_plateform=0;
        $activity_invest=0;

        if(in_array($input['source_type'],[2,3])) { //供应链
            $gList=array_column($cart_list,'goods_id');

            $d_methods=Db::name("choice_goods")->where(['goods_id'=> ['in',$gList]])->sum("is_free_shipping");

            //判断当前用户是否添加收货地址
            $address=Db::name("member_address")->where(["member_id"=>$input['member_id'],"is_default"=>1])
                ->field("m_name,m_mobile,address_detail,location_area,province,city,county")->find();
            if(empty($address)){
                returnJson(-2003,'请选择收货地址');
            }
            if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['province'])||empty($address['city'])||empty($address['county'])||empty($address['address_detail'])){
                returnJson(-2003,'收货地址信息不完整');
            }
            $province = $address['province'];
            $city = $address['city'];
            $area = $address['county'];
            $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
            $orderParam =[
                'address'=>[
                    'consignee' => $address['m_name'],
                    'phone' => $address['m_mobile'],
                    'province' => $province,
                    'city' => $city,
                    'area' => $area,
                    'street' => $street,
                    'description' => $street,
                ],
            ];
            $total_goods_num=0;
            $all_score_money=0;
            $all_coin_money=0;
            $all_delivery_fee=0;

            foreach ($cart_list  as $key=>$cart){
                $class_num++;
                $d_method=0;
                $goods_id=$cart['goods_id'];
                $spec_id=$cart['spec_id'];
                $goods_num=$cart['goods_num'];
                $goodsInfo=Db::name("choice_goods")->where(['goods_id'=>$cart['goods_id']])->find();
                $status=$goodsInfo['status'];
                $supply_delete_status=$goodsInfo['supply_delete_status'];
                $shop_status =$goodsInfo['shop_status'];
                $shop_delete_status =$goodsInfo['shop_delete_status'];
                if(empty($status)||$shop_status==2){
                    returnJson(-2003,'商品【'.$goodsInfo['title'].'】已下架');
                }
                if(empty($supply_delete_status)||empty($shop_delete_status)){
                    returnJson(-2003,'商品【'.$goodsInfo['title'].'】已删除');
                }
                //获取商品规格信息
                $spec=$this->getGoodsSpec($goods_id,$spec_id,$goodsInfo);

//                dump($spec);exit;
                $price=$spec['agreement_price'];
                $stock=$spec['stock'];
                if($goods_num>$stock){
                    returnJson(-2003,'商品【'.$goodsInfo['title']."】库存不足");
                }
                if(empty($goodsInfo['is_free_shipping'])){//不包邮
                    $d_methods+=1;
                    $d_method=1;
                }
                $gold_coin=0;
                $gold_coin_num=0;

                //可售检测
                $this->availableCheck($goodsInfo['title'],$spec['spec_value_names'],$cart['spec_id'],$cart['goods_num'],$order_sn,$orderParam);
                //价格计算
                $orderPrice=$this->computePrice($cart['goods_id'],$input['source_type'],$spec['agreement_price']);
                extract($orderPrice);

                $orderGoods[$key]["goods_num"]=$cart['goods_num'];
                $total_goods_num+=$cart['goods_num'];
                $orderGoods[$key]["score_money"]=$price;
                $orderGoods[$key]["spec_pic"]=!empty($spec['image'])?$spec['image']:$goodsInfo['cover'];
                $orderGoods[$key]["coin_money"]=$gold_coin;
                $orderGoods[$key]["spec_name"]=$spec['spec_value_names'];
                $orderGoods[$key]["goods_id"]=$cart['goods_id'];
                $orderGoods[$key]["goods_name"]=$goodsInfo['title'];
                $orderGoods[$key]["d_method"]=$d_method;
                //分销
                $orderGoods[$key]["activity_direct_push"]=$direct_push;
                $orderGoods[$key]["activity_inter_push"]=$inter_push;
                $orderGoods[$key]['activity_buyer']=$activity_buyer;
                $orderGoods[$key]['activity_company']=$activity_company;
                $orderGoods[$key]['activity_plateform']=$activity_plateform;
                $orderGoods[$key]['activity_invest']=$activity_invest;
                $orderGoods[$key]["give_coin"]=$gold_coin_num;
                if($d_method==1){//1=送货上门
                    $d_fee=0;
                    $d_type=2;
                    if(!empty($address)) {
                        $county=$address['county'];
                        if(!empty($province)&&!empty( $city)&&!empty($county)&&!empty($address['address_detail'])){
                            $rst=$this->computeFee($cart['spec_id'],$cart['goods_num'],$orderParam);
                            $d_fee=$rst['freight'];
                        }
                    }
                }else{// 包邮
                    $d_fee=0;
                    $d_type=0;
                    $sureOrder['d_method_name']="包邮";
                }
                $orderGoods[$key]["delivery_fee"]=$d_fee;
                $orderGoods[$key]["delivery_type"]=$d_type;
                $all_score_money+=$price*$cart['goods_num'];
                $all_coin_money+=$gold_coin*$cart['goods_num'];
                $all_delivery_fee+=$d_fee;
                $source_type=$input['source_type'];
            }
        }else{
            //判断是否所有商品都无需收货
            $d_methods=array_column($cart_list,"d_method");
            if(array_sum($d_methods)>0){
                if(empty($input['ma_id'])){
                    returnJson(-2003,'请选择收货地址');
                }
                //判断当前用户是否添加收货地址
                $address=Db::name("member_address")->where(["member_id"=>$input['member_id'],"ma_id"=>$input['ma_id']])->field("m_name,m_mobile,address_detail,location_area,province,city,county")->find();
                if(empty($address)){
                    returnJson(-2003,'请选择收货地址');
                }
                if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['location_area'])||empty($address['address_detail'])){
                    returnJson(-2003,'收货地址信息不完整');
                }
            }
            $specIdList=array_column($cart_list,'spec_id');
            $goodsList=Db::name("goods_spec")->alias("gs")
                ->join("mm_goods g","gs.goods_id=g.goods_id ")
                ->join("mm_goods_info gn","gs.goods_id=gn.goods_id")
                ->where(['gs.gs_id'=>['in', $specIdList]])
                ->column("g.store_id,g.goods_id,g.is_delete,g.status,g.member_id,
                  g.source_type,g.g_type,g.g_name,g.limit_number,g.cover_pic,g.store_id,
                  g.limit_start_time,g.limit_end_time,g.limit_num_status,g.limit_time_status,
                  gn.delivery_type,gn.direct_push,gn.inter_push,gn.copper_pop,gn.silver_pop,gn.gold_pop,
                 gs.num,gs.name spec_name,gs.price,gs.cost_price,gs.coin_price,gs.gold_coin_num,
                 gs.gs_id,gs.proportion,gn.distribution_method,gn.delivery_fee","gs.gs_id");
            $orderGoods=[];
            $tm=time();
            $all_score_money=0;
            $all_coin_money=0;
            $all_delivery_fee=0;
            $total_goods_num=0;
            //获取分销比例
            $setInfo = Db::name("system_config")
                ->where(['field_name' => "points_award_config"])
                ->value("field_value");
            $points_award_config = json_decode($setInfo, true);
            $buyer_rate = $points_award_config['buyer'];
            $invest_rate = $points_award_config['invest'];
            $direct_push_rate = $points_award_config['direct_push'];
            $inter_push_rate = $points_award_config['inter_push'];
            $platform_rate = $points_award_config['platform'];
            $city_company_rate = $points_award_config['city_company'];


            foreach ($cart_list as $key=>$cart){
                $class_num++;
                $d_method=0;
                //商品判断
                $goods=$goodsList[$cart['spec_id']];
                if($goods['store_id']!=$store_id){
                    returnJson(-2004,"商品不存在或数据异常");
                }
                $gName=$goods['g_name'];
                if(empty($goods['goods_id'])||$goods['is_delete']==2){
                    returnJson(-2003,'商品【'.$gName.'】不存在或已删除');
                }
                if($goods['status']!=1){
                    returnJson(-2003,'商品【'.$gName.'】未上架');
                }
                //判断是否为商家自己的商品
                if($goods['member_id']==$input["member_id"]){
                    returnJson(-2003,'商品【'.$gName.'】为当前用户商家商品');
                }
                //判断是否选中配送方式
                $distribution_method=$goods['distribution_method'];
                if($distribution_method!=0){
                    $d_method=$cart['d_method'];
                    if(empty($d_method)){
                        returnJson(-2003,"【".$goods['g_name']."】".'未选择配送方式');
                    }
                    if(!in_array($d_method,explode(",",$distribution_method))){
                        returnJson(-2003,'商品【'.$gName.'】不支持当前配送方式');
                    }
                }
                //判断商品是否限购
                if($goods['limit_num_status']==2){//限购
                    $limit_number=$goods['limit_number'];
                    //规格ID
                    $buyNums=Db::name("order_goods")->alias("og")
                        ->join("mm_order o","og.order_id=o.order_id")
                        ->where(['o.pay_status'=>2,"og.goods_id"=>$goods["goods_id"],"o.member_id"=>$input["member_id"]])
                        ->value("og.goods_num");
                    if($buyNums>=$limit_number){
                        returnJson(-2003,'商品【'.$gName.'】限购'.$limit_number);
                    }
                }
                //判断活动是否限时
                if($goods['limit_time_status']==2){//限时
                    if($tm<$goods['limit_start_time']){
                        returnJson(-2003,'商品【'.$gName.'】活动还未开始');
                    }

                    if($tm>$goods['limit_end_time']){
                        returnJson(-2003,'商品【'.$gName.'】活动已经过期');
                    }
                }
                //库存判断
                if($cart['goods_num']>$goods['num']&&!in_array($goods['g_type'],[4,5])){
                    $goodsName=Db::name("goods_spec")->alias("a")
                        ->join("mm_goods g","g.goods_id=a.goods_id")
                        ->value("g.g_name");

                    returnJson(-2004,"【".$goodsName."】".'库存不足,剩余库存');
                }
                //1=消费爆品，2=裂变爆品,3=返利，4=活动,5=讲坛',

                if(in_array($goods['g_type'],[3,5])){//返利 讲坛
                    //订单总金额（不包括运费）
                    $orderAmount = $goods['price'];
                    $proportion = $goods['proportion'];
                    $distributionScore = $orderAmount * $proportion / 100;
                    if ( $distributionScore > 0) {
                        $buyer_score = $distributionScore * $buyer_rate / 100;
                        $activity_buyer=sprintf("%.2f",substr(sprintf("%.3f", $buyer_score), 0, -2));
                        //直推
                        $direct_push_score = $distributionScore * $direct_push_rate / 100;
                        $direct_push=sprintf("%.2f",substr(sprintf("%.3f", $direct_push_score), 0, -2));
                        //间推
                        $inter_push_score = $distributionScore * $inter_push_rate / 100;
                        $inter_push=sprintf("%.2f",substr(sprintf("%.3f", $inter_push_score), 0, -2));
                        //招商
                        $activity_invest=$distributionScore * $invest_rate / 100;
                        $activity_invest=sprintf("%.2f",substr(sprintf("%.3f",  $activity_invest), 0, -2));

                        //子公司
                        $activity_company=$distributionScore * $city_company_rate / 100;
                        $activity_company=sprintf("%.2f",substr(sprintf("%.3f",$activity_company), 0, -2));
                        //平台
                        $activity_plateform=$distributionScore * $platform_rate / 100;
                        $activity_plateform=sprintf("%.2f",substr(sprintf("%.3f",  $activity_plateform), 0, -2));
                    }else{
                        $activity_invest=0;
                        $direct_push=0;
                        $inter_push=0;
                        $activity_buyer=0;
                        $activity_company=0;
                        $activity_plateform=0;
                    }
                }elseif($goods['g_type']==4){//限时特惠
                    $direct_push=$goods['direct_push'];
                    $inter_push=$goods['inter_push'];
                    $activity_buyer=0;
                    $activity_company=0;
                    $activity_plateform=0;
                    $activity_invest=0;
                }elseif($goods['g_type']==6){
                    $direct_push=0;
                    $inter_push=0;
                    $activity_buyer=0;
                    $activity_company=0;
                    $activity_plateform=0;
                    $activity_invest=0;
                }

                $orderGoods[$key]["spec_id"]=$goods['gs_id'];
                $orderGoods[$key]["proportion"]=$goods['proportion'];
                $orderGoods[$key]["give_coin"]=$goods['gold_coin_num'];
                $orderGoods[$key]["copper"]=$goods['copper_pop'];
                $orderGoods[$key]["silver"]=$goods['silver_pop'];
                $orderGoods[$key]["golden"]=$goods['gold_pop'];
                $orderGoods[$key]["goods_num"]=$cart['goods_num'];
                $orderGoods[$key]["score_money"]=$goods['price'];
                $orderGoods[$key]["spec_pic"]=$goods['cover_pic'];
                $orderGoods[$key]["coin_money"]=$goods['coin_price'];
                $orderGoods[$key]["spec_name"]=$goods['spec_name'];
                $orderGoods[$key]["goods_id"]=$goods['goods_id'];
                $orderGoods[$key]["goods_name"]=$goods['g_name'];
                $orderGoods[$key]["og_d_status"]=1;
                $orderGoods[$key]["create_time"]= $tm;
                $orderGoods[$key]["update_time"]= $tm;
                $orderGoods[$key]["d_method"]=$d_method;
                //分销
                $orderGoods[$key]["activity_direct_push"]=$direct_push;
                $orderGoods[$key]["activity_inter_push"]=$inter_push;
                $orderGoods['activity_buyer']=$activity_buyer;
                $orderGoods['activity_company']=$activity_company;
                $orderGoods['activity_plateform']=$activity_plateform;
                $orderGoods['activity_invest']=$activity_invest;
                if($d_method==1){//1=送货上门
                    if($goods['delivery_type']==1){//商家自己配送
                        $d_fee=$goods['delivery_fee'];
                        $d_type=1;
                    }elseif($goods['delivery_type']==2) {//第三方配送

                        $d_fee=10;
                        $d_type=2;
                    }

                }elseif($d_method==2){//2=到店消费
                    $d_fee=0;
                    $d_type=0;
                }
                $orderGoods[$key]["delivery_fee"]=$d_fee;
                $orderGoods[$key]["delivery_type"]=$d_type;
                $all_score_money+=$goods['price']*$cart['goods_num'];
                $all_coin_money+=$goods['coin_price']*$cart['goods_num'];
                $all_delivery_fee+=$d_fee;
                $total_goods_num+=$cart['goods_num'];
            }
        }

        if($d_methods>0){
            if(!empty($address)){
                $sureOrder['receiver']=$address['m_name'];
                $sureOrder['re_phone']=$address['m_mobile'];
                $sureOrder['address']=$address['location_area'].$address['address_detail'];
            }else{
                $sureOrder['receiver']='';
                $sureOrder['re_phone']='';
                $sureOrder['address']='';
            }
            $sureOrder['is_deliver']=1;
        }else{
            $sureOrder['is_deliver']=0;
        }

        $pay_method=$input['pay_method'];
        $pay_method_arr=explode(",",$pay_method);
        $orderData=[];
        $orderData['ma_id']=$input['ma_id'];
        $orderData['order_sn']=$order_sn;
        $orderData['source_type']=$input['source_type'];
        $orderData['status']=1;
        $orderData['pay_status']=1;
        $orderData['goods_class']=$class_num;
        $orderData['member_id']=$input['member_id'];
        $orderData['store_id']=$input['store_id'];
        $orderData['order_score_money']=$all_score_money;
        $orderData['order_coin_money']=$all_coin_money;
        $orderData['order_delivery_fee']=$all_delivery_fee;
        if(!empty($address)){
            $orderData['receiver']=$address['m_name'];
            $orderData['re_phone']=$address['m_mobile'];
            $orderData['address']=$address['location_area'].$address['address_detail'];
        }
        $orderData['create_time']=$tm;
        $orderData['update_time']=$tm;
        $orderData['is_del']=1;
        //获取用户资产
        $coin_money=0;
        $score_money=0;
        $wx_money=0;
        $memberAsset=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->field("score,coin")->find();
        if($all_coin_money==0){//积分或现金支付
            $orderAmount=$all_score_money+$all_delivery_fee;
            if(in_array(1,$pay_method_arr)) {//积分支付
                if($memberAsset['score']>$orderAmount){
                    $score_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $score_money=$memberAsset['score'];
                    $wx_money=$orderAmount-$memberAsset['score'];
                }
            }else{
                $wx_money= $orderAmount=$all_score_money+$all_delivery_fee;
            }
        }else{//积分+现金支付+金币
            if(in_array(1,$pay_method_arr)&&in_array(2,$pay_method_arr)){//积分+金币+微信支付
                if($memberAsset['coin']>$all_coin_money){//用户金币足够
                    $coin_money=$all_coin_money;
                    $orderAmount=$all_score_money+$all_delivery_fee;
                    if($memberAsset['score']>$orderAmount){
                        $score_money=$orderAmount-0.01;
                        $wx_money='0.01';
                    }else{
                        $score_money=$memberAsset['score'];
                        $wx_money=$orderAmount-$memberAsset['score'];
                    }
                }else{
                    $coin_money=$memberAsset['coin'];
                    $orderAmount=$all_coin_money+$all_score_money+$all_delivery_fee-$coin_money;
                    if($memberAsset['score']>$orderAmount){
                        $score_money=$orderAmount-0.01;
                        $wx_money='0.01';
                    }else{
                        $score_money=$memberAsset['score'];
                        $wx_money=$orderAmount-$memberAsset['score'];
                    }
                }
            }elseif(in_array(1,$pay_method_arr)){//积分支付
                $orderAmount=$all_score_money+$all_delivery_fee+$all_coin_money;
                if($memberAsset['score']>$orderAmount){
                    $score_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $score_money=$memberAsset['score'];
                    $wx_money=$orderAmount-$memberAsset['score'];
                }

            }elseif(in_array(2,$pay_method_arr)){//金币+现金支付
                $orderAmount=$all_score_money+$all_delivery_fee+$all_coin_money;
                if($memberAsset['coin']>$orderAmount){
                    $coin_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $coin_money=$memberAsset['coin'];
                    $wx_money=$orderAmount-$memberAsset['coin'];
                }

            }else{
                $wx_money=$all_score_money+$all_delivery_fee+$all_coin_money;
            }

        }
        if(($all_score_money+$all_coin_money+$all_delivery_fee)!=($coin_money+$score_money+$wx_money)){
            returnJson(-2004,'订单金额计算失败');
        }else{
            $orderData['wx_money']=$wx_money;
            $orderData['score_money']=$score_money;
            $orderData['coin_money']=$coin_money;
        }

        Db::startTrans();
        try{

            $orderID=Db::name("order")->insertGetId($orderData);
            if($orderID<=0){
                throw new Exception("更新失败5");
            }

            if($score_money>0){//写入积分冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$score_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>1,'log_type_id'=>53,
                        'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败4");
                }
            }
            if($coin_money>0){//写入金币冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$coin_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>2,'log_type_id'=>54,
                        'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败3");
                }
            }

            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score-$score_money,frozen_score=frozen_score+$score_money,pay_frozen_score=pay_frozen_score+$score_money,coin=coin-$coin_money,frozen_coin=frozen_coin+$coin_money where member_id=".$input['member_id']." and score>=$score_money and coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败2");
                }
            }

            foreach ($orderGoods as &$goodsItem){
                $goodsItem["order_id"]=$orderID;
            }

            $num=Db::name("order_goods")->insertAll($orderGoods);

            if($num<=0){
                throw new Exception("更新失败1");
            }

            $result=$this->orderPay($order_sn,$input['member_id']);
            Db::commit();
            returnJson(200,'订单创建成功',$result);
        }catch (Exception $e){
            Db::rollback();

            returnJson(-2004,"订单创建失败");
        }
    }

    /**
     * 确认订单
     */
    public function getSureOrder($data){
        $tm=time();
        $d_method=0;
        $activity_buyer=0;

        if(in_array($data['source_type'],[2,3])){
             //库存判断
            //判断商品状态
            $goodsInfo=Db::name("choice_goods")->where(['goods_id'=>$data['goods_id']])->find();
            $status=$goodsInfo['status'];
            $supply_delete_status=$goodsInfo['supply_delete_status'];
            $shop_status =$goodsInfo['shop_status'];
            $shop_delete_status =$goodsInfo['shop_delete_status'];

            if(empty($status)||$shop_status==2){
                returnJson(-2003,'商品已下架');
            }
            if(empty($supply_delete_status)||empty($shop_delete_status)){
                returnJson(-2003,'商品已删除');
            }
            //获取商品规格信息
            $spec=$this->getGoodsSpec($data['goods_id'],$data['spec_id'],$goodsInfo);
            $stock=$spec['stock'];
            if($data['goods_num']>$stock){
                returnJson(-2003,"库存不足");
            }
            if(empty($goodsInfo['is_free_shipping'])){//不包邮
                $d_method=1;
            }
            #处理价格数据
            $orderPrice=$this->computePrice($data['goods_id'],$data['source_type'],$spec['agreement_price']);
            extract($orderPrice);

            $gold_coin_num=0;
            $gold_coin=0;
            $price=$spec['agreement_price'];

            $rebate_score=$activity_buyer;
            $rebate_coin=$gold_coin_num;
            $goods=[];
            $goods_spec=[];
            $goods_spec['name']=$spec['spec_value_names'];
            $goods['g_name']=$goodsInfo['title'];
            //$goods['store_id']=$goodsInfo['source'];
            $goods['store_id']=0;
            $goods['cover_pic']=!empty($spec['image'])?$spec['image']:$goodsInfo['cover'];
            $goods_spec['price']= $price;
            $goods_spec['coin_price']=$gold_coin;
        }
        else{
            //获取商品主要信息
            $goods=Db::name("goods")->where(['goods_id'=>$data["goods_id"]])
                ->field("g_type,cover_pic,source_type,g_name,member_id,goods_id,store_id,source_type,
                is_delete,limit_number,limit_start_time,limit_end_time,limit_num_status,limit_time_status,status")
                ->find();
            if(empty($goods['goods_id'])||$goods['is_delete']==2){
                returnJson(-2003,'当前商品不存在或已删除');
            }
            if($goods['status']!=1){
                returnJson(-2003,'当前商品未上架');
            }
            //判断是否为商家自己的商品
            if($goods['member_id']==$data["member_id"]){
                returnJson(-2003,'当前商品为当前用户商家商品');
            }
            //判断是否选中配送方式
            $goodsInfo=Db::name("goods_info")
                ->where(['goods_id'=>$data["goods_id"]])
                ->field("distribution_method,delivery_type,delivery_fee")
                ->find();
            $distribution_method=$goodsInfo['distribution_method'];
            if($distribution_method>0){
                $d_method=$data['d_method'];
                if(empty($d_method)){
                    returnJson(-2003,'请选中配送方式');
                }
                if(!in_array($d_method,array(1,2))){
                    returnJson(-2003,'当前商品不支持当前配送方式');
                }
            }
            //判断商品是否限购
            if($goods['limit_num_status']==2){//限购
                $limit_number=$goods['limit_number'];
                //规格ID
                $buyNums=Db::name("order_goods")->alias("og")
                    ->join("mm_order o","og.order_id=o.order_id")
                    ->where(['o.pay_status'=>2,"og.goods_id"=>$data["goods_id"],"o.member_id"=>$data["member_id"]])
                    ->value("og.goods_num");
                if($buyNums>=$limit_number){
                    returnJson(-2003,"当前商品限购".$limit_number);
                }
            }
            //判断活动是否限时
            if($goods['limit_time_status']==2){//限时
                if($tm<$goods['limit_start_time']){
                    returnJson(-2003,'当前商品活动还未开始');
                }

                if($tm>$goods['limit_end_time']){
                    returnJson(-2003,'当前商品活动已经过期');
                }
            }
            //获取商品规格及相关信息
            $goods_spec=Db::name("goods_spec")
                ->where(['goods_id'=>$data['goods_id'],'gs_id'=>$data['spec_id']])
                ->field("name,num,price,coin_price")
                ->find();

            if($goods_spec['num']<$data['goods_num']&&!in_array($goods['g_type'],[4,5])){
                returnJson(-2003,'当前规格商品库存不足');
            }
        }
        $sureOrder=array();

        if($d_method>0){
            //获取收货人信息
            $address=Db::name("member_address")
                ->where(["member_id"=>$data['member_id'],"is_default"=>1])
                ->field("m_name,m_mobile,address_detail,location_area,province,city,county")
                ->find();
            if(!empty($address)) {
                $sureOrder['receiver']=$address['m_name'];
                $sureOrder['re_phone']=$address['m_mobile'];
                $sureOrder['address']=$address['location_area'].$address['address_detail'];
            }
        }

        //获取商品信息
        if(!empty($rebate_coin)){
            $sureOrder['rebate_coin']=$rebate_coin;
        }
        if(!empty($rebate_score)){
            $sureOrder['rebate_score']=$rebate_score;
        }
        $sureOrder['goods_name']=$goods['g_name'];
        $sureOrder['store_id']=$goods['store_id'];
        $sureOrder['spec_id']=$data['spec_id'];
        $sureOrder['goods_id']=$data['goods_id'];
        $sureOrder['cover_pic']=$goods['cover_pic'];
        $sureOrder['spec_name']= $goods_spec['name'];
        $sureOrder['goods_num']=$data['goods_num'];
        $sureOrder['goods_score']=$goods_spec['price'];
        $sureOrder['goods_coin']=$goods_spec['coin_price'];
        $sureOrder['d_fee']=0;
        if(in_array($data['source_type'],[2,3])){//供应链
            if($goodsInfo['is_free_shipping']==1){//包邮
                $sureOrder['d_method_name']="包邮";
                $sureOrder['d_fee']=0;
            }else{//计算运费
                $sureOrder['d_fee']=0;

                if(!empty($address)) {

                    $province=$address['province'];
                    $city=$address['city'];
                    $county=$address['county'];
                    if(!empty($province)&&!empty( $city)&&!empty($county)&&!empty($address['address_detail'])){

                        $area = $address['county'];
                        $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
                        $orderParam =[
                            'address'=>[
                                'consignee' => $address['m_name'],
                                'phone' => $address['m_mobile'],
                                'province' => $province,
                                'city' => $city,
                                'area' => $area,
                                'street' => $street,
                                'description' => $street,
                            ],
                        ];
                        $rst=$this->computeFee($data['spec_id'],$data['goods_num'],$orderParam);
                        $sureOrder['d_fee']=$rst['freight'];
                    }
                }
            }
            if($goodsInfo['source']==1){
                $sureOrder['store_name']="自营店铺";
            }elseif($goodsInfo['source']==2){
                $sureOrder['store_name']="京东商城";
            }elseif($goodsInfo['source']==6){
                $sureOrder['store_name']="阿里巴巴";
            }elseif($goodsInfo['source']==7){
                $sureOrder['store_name']="天猫商城";
            }
        }
        else{
            //获取店铺名称
            if($data['source_type']==4){
                $sureOrder['store_name']="自营店铺";
            }else{
                $storeName=Db::name("store_apply")->where(['sa_id'=>$goods['store_id']])->value("company_name");

                if($goods['source_type']==1){
                    $sureOrder['store_name']="联盟商家-".$storeName;
                }else{
                    $sureOrder['store_name']=$storeName;
                }
            }


            if($d_method==1){//送货上门
                $sureOrder['d_method_name']="送货上门";
                if($goodsInfo['delivery_type']==1){//自己配送
                    $sureOrder['d_fee']=Db::name("store_detail")
                        ->where(['sa_id'=>$goods['store_id']])
                        ->value("delivery_fee");;
                }elseif($goodsInfo['delivery_type']==2){//第三方配送

                }
            }elseif($d_method==2){//到店消费
                $sureOrder['d_method_name']="到店消费";
                $sureOrder['d_fee']=0;
            }
        }
        $sureOrder['d_method']=$d_method;//配送方式
        //合计
        $score_money=$goods_spec['price']*$data['goods_num'];
        $coin_money=$goods_spec['coin_price']*$data['goods_num'];
        $delivery_fee=$sureOrder['d_fee'];
        $goods_num=$data['goods_num'];
        $sureOrder['total_score_money']=$score_money;
        $sureOrder['total_coin_money']=$coin_money;
        $sureOrder['total_delivery_fee']=$delivery_fee;
        $sureOrder['total_goods_num']=$goods_num;
        //用户余额
        $assert=Db::name("member_asset")
            ->where(['member_id'=>$data['member_id']])
            ->find();
        $sureOrder['mem_score']=$assert['score']?$assert['score']:'0.00';
        $sureOrder['mem_coin']=$assert['coin']?$assert['coin']:'0.00';

        return $sureOrder;

    }


    /**
     * 购物车确认订单
     */
    public function getCartSureOrder($input){

        $member_id=$input['member_id'];
        $cart_list=$input['cart_list'];
        $store_id=$input['store_id'];
        $tm=time();
        $cart_list=json_decode($cart_list,true);
//        $cart_list=[
//           // ['goods_id'=>599709,'spec_id'=>2697683,'goods_num'=>1,'d_method'=>0],
//           // ['goods_id'=>24,'spec_id'=>49,'goods_num'=>1,'d_method'=>1],
//            ['goods_id'=>599709,'spec_id'=>2697683,'goods_num'=>1,'d_method'=>0],
//        ];

        $orderGoods=[];
        $score_money=0;
        $coin_money=0;
        $delivery_fee=0;
        $total_goods_num=0;
        $d_methods=0;
        $activity_buyer=0;

        if(in_array($input['source_type'],[2,3])) {//供应链
            $address=Db::name("member_address")->where(["member_id"=>$input['member_id'],"is_default"=>1])
                ->field("m_name,m_mobile,address_detail,location_area,province,city,county")->find();

            foreach ($cart_list  as $key=>$cart){
                $d_method=0;
                $goods_id=$cart['goods_id'];
                $spec_id=$cart['spec_id'];
                $goods_num=$cart['goods_num'];
                $goodsInfo=Db::name("choice_goods")->where(['goods_id'=>$cart['goods_id']])->find();
                $status=$goodsInfo['status'];
                $supply_delete_status=$goodsInfo['supply_delete_status'];
                $shop_status =$goodsInfo['shop_status'];
                $shop_delete_status =$goodsInfo['shop_delete_status'];

                if(empty($status)||$shop_status==2){
                    returnJson(-2003,'商品【'.$goodsInfo['title'].'】已下架');
                }
                if(empty($supply_delete_status)||empty($shop_delete_status)){
                    returnJson(-2003,'商品【'.$goodsInfo['title'].'】已删除');
                }
                //获取商品规格信息
                $spec=$this->getGoodsSpec($goods_id, $spec_id,$goodsInfo);
                $stock=$spec['stock'];
                if($goods_num>$stock){
                    returnJson(-2003,'商品【'.$goodsInfo['title']."】库存不足");
                }
                if(empty($goodsInfo['is_free_shipping'])){//不包邮
                    $d_methods+=1;
                    $d_method=1;
                }
                $gold_coin_num=0;
                $gold_coin=0;
                $price=$spec['agreement_price'];

                //价格计算
                $orderPrice=$this->computePrice($cart['goods_id'],$input['source_type'],$spec['agreement_price']);
                extract($orderPrice);
                $rebate_score=$activity_buyer;
                $rebate_coin=$gold_coin_num;

                $orderGoods[$key]['rebate_coin']=$rebate_coin;
                $orderGoods[$key]['rebate_score']=$rebate_score;

                $orderGoods[$key]['store_id']=0;
                $orderGoods[$key]["goods_num"]=$cart['goods_num'];
                $total_goods_num+=$cart['goods_num'];
                $orderGoods[$key]["score_money"]=$price;
                $orderGoods[$key]["spec_pic"]=!empty($spec['image'])?$spec['image']:$goodsInfo['cover'];
                $orderGoods[$key]["coin_money"]=$gold_coin;
                $orderGoods[$key]["spec_name"]=$spec['spec_value_names'];
                $orderGoods[$key]["goods_id"]=$cart['goods_id'];
                $orderGoods[$key]["goods_name"]=$goodsInfo['title'];

                $orderGoods[$key]["d_method"]=$d_method;
                if($d_method==1){//1=送货上门
                        $d_fee=0;
                        $d_type=2;
                        if(!empty($address)) {

                            $province=$address['province'];
                            $city=$address['city'];
                            $county=$address['county'];
                            if(!empty($province)&&!empty( $city)&&!empty($county)&&!empty($address['address_detail'])){
                                $area = $address['county'];
                                $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
                                $orderParam =[
                                    'address'=>[
                                        'consignee' => $address['m_name'],
                                        'phone' => $address['m_mobile'],
                                        'province' => $province,
                                        'city' => $city,
                                        'area' => $area,
                                        'street' => $street,
                                        'description' => $street,
                                    ],
                                ];
                                $rst=$this->computeFee($cart['spec_id'],$cart['goods_num'],$orderParam);
                                $d_fee=$rst['freight'];
                            }
                        }
                }else{// 包邮
                    $d_fee=0;
                    $d_type=0;
                    $sureOrder['d_method_name']="包邮";
                }
                $orderGoods[$key]["delivery_fee"]=$d_fee;
                $orderGoods[$key]["delivery_type"]=$d_type;
                $score_money+=$price*$cart['goods_num'];
                $coin_money+=$gold_coin*$cart['goods_num'];

                $delivery_fee+=$d_fee;

                $source_type=$input['source_type'];
            }

        }else{
            $specIdList=array_column($cart_list,'spec_id');
            $goodsList=Db::name("goods_spec")->alias("gs")
                ->join("mm_goods g","gs.goods_id=g.goods_id ")
                ->join("mm_goods_info gn","gs.goods_id=gn.goods_id")
                ->where(['gs.gs_id'=>['in', $specIdList]])
                ->column("g.store_id,g.goods_id,g.is_delete,g.status,g.member_id,
                  g.source_type,g.g_type,g.g_name,g.limit_number,g.cover_pic,g.store_id,
                  g.limit_start_time,g.limit_end_time,g.limit_num_status,g.limit_time_status,
                  gn.delivery_type,
                 gs.num,gs.name spec_name,gs.price,gs.cost_price,gs.coin_price,gs.gold_coin_num,
                 gs.gs_id,gs.proportion,gn.distribution_method,gn.delivery_fee","gs.gs_id");

            foreach ($cart_list as $key=>$cart){
                $d_method=0;
                //商品判断
                $goods=$goodsList[$cart['spec_id']];
                if($goods['store_id']!=$store_id){
                    returnJson(-2004,"商品不存在或数据异常");
                }
                $gName=$goods['g_name'];
                if(empty($goods['goods_id'])||$goods['is_delete']==2){
                    returnJson(-2003,'商品【'.$gName.'】不存在或已删除');
                }
                if($goods['status']!=1){
                    returnJson(-2003,'商品【'.$gName.'】未上架');
                }
                //判断是否为商家自己的商品
                if($goods['member_id']==$input["member_id"]){
                    returnJson(-2003,'商品【'.$gName.'】为当前用户商家商品');
                }
                //判断是否选中配送方式
                $distribution_method=$goods['distribution_method'];

                if($distribution_method!=0){
                    $d_method=$cart['d_method'];
                    if(empty($d_method)){
                        returnJson(-2003,"【".$goods['g_name']."】".'未选择配送方式');
                    }
                    if(!in_array($d_method,explode(",",$distribution_method))){
                        returnJson(-2003,'商品【'.$gName.'】不支持当前配送方式');
                    }
                }
                //判断商品是否限购
                if($goods['limit_num_status']==2){//限购
                    $limit_number=$goods['limit_number'];
                    //规格ID
                    $buyNums=Db::name("order_goods")->alias("og")->join("mm_order o","og.order_id=o.order_id")->where(['o.pay_status'=>2,"og.goods_id"=>$goods["goods_id"],"o.member_id"=>$input["member_id"]])->value("og.goods_num");
                    if($buyNums>=$limit_number){
                        returnJson(-2003,'商品【'.$gName.'】限购'.$limit_number);
                    }
                }
                //判断活动是否限时
                if($goods['limit_time_status']==2){//限时
                    if($tm<$goods['limit_start_time']){
                        returnJson(-2003,'商品【'.$gName.'】活动还未开始');
                    }

                    if($tm>$goods['limit_end_time']){
                        returnJson(-2003,'商品【'.$gName.'】活动已经过期');
                    }
                }
                //库存判断
                if($cart['goods_num']>$goods['num']&&!in_array($goods['g_type'],[4,5])){
                    $goodsName=Db::name("goods_spec")->alias("a")->join("mm_goods g","g.goods_id=a.goods_id")->value("g.g_name");

                    returnJson(-2004,"【".$goodsName."】".'库存不足,剩余库存');
                }

                $d_methods+=$cart['d_method'];
                $orderGoods[$key]["goods_num"]=$cart['goods_num'];
                $total_goods_num+=$cart['goods_num'];
                $orderGoods[$key]["score_money"]=$goods['price'];
                $orderGoods[$key]["spec_pic"]=$goods['cover_pic'];
                $orderGoods[$key]["coin_money"]=$goods['coin_price'];
                $orderGoods[$key]["spec_name"]=$goods['spec_name'];
                $orderGoods[$key]["goods_id"]=$goods['goods_id'];
                $orderGoods[$key]["goods_name"]=$goods['g_name'];

                $orderGoods[$key]["d_method"]=$d_method;
                if($d_method==1){//1=送货上门
                    if($goods['delivery_type']==1){//商家自己配送
                        $d_fee=$goods['delivery_fee'];
                        $d_type=1;
                    }elseif($goods['delivery_type']==2) {//第三方配送
                        $d_fee=10;
                        $d_type=2;
                    }

                }elseif($d_method==2){//2=到店消费
                    $d_fee=0;
                    $d_type=0;
                }
                $orderGoods[$key]["delivery_fee"]=$d_fee;
                $orderGoods[$key]["delivery_type"]=$d_type;
                $score_money+=$goods['price']*$cart['goods_num'];
                $coin_money+=$goods['coin_price']*$cart['goods_num'];
                $delivery_fee+=$d_fee;

                $source_type=$goods['source_type'];

            }
        }
        //判断是否所有商品都无需收货
        if($d_methods>0){
            //判断当前用户是否添加收货地址
            $address=Db::name("member_address")->where(["member_id"=>$input['member_id'],"is_default"=>1])->field("m_name,m_mobile,address_detail,location_area,province,city,county")->find();
        }
        if(in_array($input['source_type'],[2,3])) {//供应链
            $sureOrder['store_name']="第三方商城";
        }else{
            if($input['source_type']==5){
                $sureOrder['store_name']="自营店铺";
            }else{
                //获取商家名称
                $storeName=Db::name("store_apply")->where(['sa_id'=>$input['store_id']])->value("company_name");
                if($source_type==1){
                    $sureOrder['store_name']="联盟商家-".$storeName;
                }else{
                    $sureOrder['store_name']=$storeName;
                }
            }

        }

        if($d_methods>0){
            if(!empty($address)){
                $sureOrder['receiver']=$address['m_name'];
                $sureOrder['re_phone']=$address['m_mobile'];
                $sureOrder['address']=$address['location_area'].$address['address_detail'];

            }else{
                $sureOrder['receiver']='';
                $sureOrder['re_phone']='';
                $sureOrder['address']='';
            }

            $sureOrder['is_deliver']=1;
        }else{
            $sureOrder['is_deliver']=0;
        }
        $sureOrder['store_id']=$input['store_id'];
        $sureOrder['goods_spec_list']=$orderGoods;
        $sureOrder['total_score_money']=$score_money;
        $sureOrder['total_coin_money']=$coin_money;
        $sureOrder['total_delivery_fee']=$delivery_fee;
        $sureOrder['total_goods_num']= $total_goods_num;
        //用户余额
        $assert=Db::name("member_asset")->where(['member_id'=>$member_id])->find( );
        $sureOrder['mem_score']=$assert['score']?$assert['score']:'0.00';
        $sureOrder['mem_coin']=$assert['coin']?$assert['coin']:'0.00';
        $sureOrder['cart_list']=$cart_list;
        returnJson(200,'success',$sureOrder);
    }

    /**
     * 取消支付
     */
    public function cancelOrder($input){

        $order_sn=$input['order_sn'];
        $member_id=$input['member_id'];
        //获取当前记录
        $payInfo=Db::name("order")->where(['member_id'=>$member_id,"order_sn"=>$order_sn,'status'=>['not in',[2,7]]])->field("order_id,score_money,coin_money")->find();
        $coin_money= $payInfo['coin_money'];
        $score_money= $payInfo['score_money'];
        $orderID= $payInfo['order_id'];
        Db::startTrans();
        try {
            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score+$score_money,frozen_score=frozen_score-$score_money,pay_frozen_score=pay_frozen_score-$score_money,coin=coin+$coin_money,frozen_coin=frozen_coin-$coin_money where member_id=".$member_id." and frozen_score>=$score_money  and pay_frozen_score>=$score_money and frozen_coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            $num=Db::name("order")->where(['member_id'=>$member_id,"order_sn"=>$order_sn])->update(['status'=>7]);
            if($num<=0){
                throw new Exception("更新失败");
            }
            $num=Db::name("member_asset_log")->where(['member_id'=>$member_id,'relation_id'=>$orderID,"log_type_id"=>['in',[53,54]]])->delete();
            if($num<=0){
                throw new Exception("更新失败");
            }
            Db::commit();
            return ['order_sn'=>$order_sn];
        }catch (Exception $e){
            Db::rollback();
            returnJson(-2004,"操作失败");
        }
    }

    /**
     * 微信支付
     */
     public function orderPay($order_sn,$member_id){
         #获取openid
         $openid = Db::name("member")
             ->field("openid")
             ->where(['member_id'=>$member_id])
             ->value("openid");
         //获取订单信息
         $orderInfo=Db::name("order")->where(['order_sn'=>$order_sn])->field("order_id,wx_money,source_type")->find();
         $order_id=$orderInfo['order_id'];
         $total_fee=$orderInfo['wx_money'];
         $orderGoods=Db::name("order_goods")->where(['order_id'=>$order_id])->field("goods_id")->select();
         $goodsList=array_column( $orderGoods,'goods_id');
         if(in_array( $orderInfo['source_type'],[2,3])){
             $goodsArr=Db::name("choice_goods")->where(['goods_id'=>['in',$goodsList]])->field("title g_name")->select();
         }else{
             $goodsArr=Db::name("goods")->where(['goods_id'=>['in',$goodsList]])->field("g_name")->select();
         }
         $body                = implode(";",array_column($goodsArr,'g_name'));

         $notify_url =  request()->domain()."/index.php/applet/Notify/orderPayment";

        // returnJson(-2004,["openid"=>$openid,"body"=>$body,"total_fee"=>$total_fee,'notify_url'=>$notify_url,"order_sn"=>$order_sn]);
         #调取支付接口
         $weixinPay = new WeixinPay($openid, $body, $total_fee, $order_sn,$notify_url);
         // 发起微信支付
         $result = $weixinPay->pay();
         $result['order_id']=$order_id;
         $result['order_sn']=$order_sn;
         return $result;
     }

    /**
     * 供应链订单计算价格
     */

    public function computePrice($goods_id,$source_type,$agreement_price){


        if($source_type==2){//返利商城
            $getReturnPop=getReturnPop($goods_id,1);
            $price= sprintf("%.1f",$agreement_price * $getReturnPop / 100);
            $gold_coin_num=0;
            $gold_coin=0;
            $direct_push=$agreement_price / 100* 0.05 ;
            $inter_push=$agreement_price / 100* 0.05 ;
            $activity_buyer=$agreement_price / 100* 0.2;
            $activity_plateform=$agreement_price/ 100* 0.2;
            $activity_invest=0;
            $activity_company=0;
        }elseif($source_type==3){//爆品商城
            $getReturnPop=getReturnPop($goods_id,2);
            $price = sprintf("%.1f",$agreement_price * $getReturnPop / 100);
            $gold_coin = sprintf("%.1f",$agreement_price * $getReturnPop * 2 / 100);
            $gold_coin_num=0;
            $direct_push=0;//直推
            $inter_push=0;//间推
            $activity_buyer=0;//买家
            $activity_plateform=0;//平台
            $activity_invest=0;//招商
            $activity_company=0;//子公司
        }
        return ['price'=>$price,'gold_coin'=>$gold_coin,'direct_push'=>$direct_push,
            'inter_push'=>$inter_push,'activity_buyer'=>$activity_buyer,'activity_plateform'=>$activity_plateform,
            'activity_invest'=>$activity_invest,'activity_company'=>$activity_company,'gold_coin_num'=>$gold_coin_num];

    }

    /**
     *获取供应链商品规格信息
     */
    public function getGoodsSpec($goods_id,$spec_id,$goodsInfo){
        //获取当前规格价格
        $method = 'GET';//请求方法
        $action = '/v2/Goods/Detail';//请求资源名
        $this->client = new SupplyClient( $this->appKey, $this->appSecret);
        $response = $this->client->getApiResponse($method,$action,['id'=> $goods_id]);
        $response = json_decode($response,true);
        if($response['code'] !== 1)
        {
            returnJson(-2004,'商品【'.$goodsInfo['title']."】ID异常");
        }
        $response = $response['data'];
        $optionsList=$response["specs"]['options'];
        $isExt=false;
        foreach ( $optionsList as $option){
            if($option['id']==$spec_id){
                $spec=$option;
                $isExt=true;
            }
        }

        if(empty($isExt)){
            returnJson(-2003,'商品【'.$goodsInfo['title']."】该规格不存在");
        }

        return  $spec;

    }


    /**
     * 供应链订单可售检测
     */
    public function availableCheck($title,$spec_value_names,$spec_id,$goods_num,$order_sn,$orderParam){
        //可售检测
        if(isset($orderParam['spu'])){
            unset($orderParam['spu']);
        }
        if(isset($orderParam['orderSn'])){
            unset($orderParam['orderSn']);
        }
        $orderParam['spu']=[[
                'sku'=>intval($spec_id),
                'number'=>intval($goods_num),],];
        $orderParam['orderSn']=$order_sn;

        $this->client = new SupplyClient( $this->appKey, $this->appSecret);
        $response = $this->client->getApiResponse("get","/v2/order/availableCheck", $orderParam);
        $response=json_decode($response,true);
        if($response['code']==1){
            $available=$response['data']['data']['available'];
            if(!in_array(intval($spec_id),$available)){
                returnJson(-2004,'商品【'.$title."】:".$spec_value_names."已下架");
            }

        }else{
            returnJson(-2004,$response['msg']);
        }
    }

    /**
     * 供应链计算运费
     */
    public function computeFee($spec_id,$goods_num,$orderParam)
    {
        $orderParam['spu'] = [
                [
                    'sku'=>intval($spec_id),
                    'number'=>intval($goods_num),
                ]];
        $method = 'POST';//请求方法
        $action = '/v2/order/beforeCheck';//请求资源名
        $this->client = new SupplyClient( $this->appKey, $this->appSecret);
        $response = $this->client->getApiResponse($method,$action, $orderParam);
        $response = json_decode($response,true);
        if($response['code'] === 10002)
        {
            $msg=$response['msg'];
            if($msg=='网络错误网络错误，请稍后重试'){
                $msg="商品库存不足";
            }
            returnJson(-2004,$msg);
        }
        if($response['code'] === -1)
        {
            returnJson(-2004,"商品规格ID异常");
        }
        if($response['code'] === 99999)
        {
            returnJson(-2004,"签名错误：算法错误");
        }

        if($response['code'] !=1)
        {
            returnJson(-2004,$response['msg']);
        }
        $response = $response['data'][0];
        $return_data['freight'] = $response['freight'] / 100;
        $return_data['sku_id'] = $response['skus'][0];

        return $return_data;
    }

    /**
     * 更改地址计算运费
     */
    public function computeOrderFee($input){
        $goods_id=$input['goods_id'] ;
        $member_id=$input['member_id'] ;
        $spec_id=$input['spec_id'] ;
        $ma_id=$input['ma_id'];

        $address=Db::name("member_address")->where(['member_id'=>$member_id,'ma_id'=>$ma_id])->find();
        if(empty($address)){
            returnJson(-2003,'请选择收货地址');
        }
        if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['province'])||empty($address['city'])||empty($address['county'])||empty($address['address_detail'])){
            returnJson(-2003,'收货地址信息不完整');
        }
        $province = $address['province'];
        $city = $address['city'];
        $area = $address['county'];
        $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
        $orderParam =[
            'address'=>[
                'consignee' => $address['m_name'],
                'phone' => $address['m_mobile'],
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'description' => $street,
            ],
        ];
        if(in_array($input['source_type'],[2,3])){//供应链

            $goodsInfo=Db::name("choice_goods")
                ->where(['goods_id'=>$goods_id])
                ->column('title,is_free_shipping','goods_id');
            $total_shipping_fee=0;
            $goods_num=$input['goods_num'];
            $spec=$this->getGoodsSpec($goods_id, $spec_id,$goodsInfo);
            $stock=$spec['stock'];
            if($goods_num>$stock){
                returnJson(-2003,'商品【'.$goodsInfo['title']."】库存不足");
            }
            if(empty($goodsInfo['is_free_shipping'])){//不包邮

                $rst=$this->computeFee($spec_id,$goods_num,$orderParam);
                $total_shipping_fee=$rst['freight'];
            }
            $gold_coin=0;
            $price=$spec['agreement_price'];

            //价格计算
            $orderPrice=$this->computePrice($goods_id,$input['source_type'],$spec['agreement_price']);
            extract($orderPrice);
            $total_score= $price*$goods_num;
            $total_coin= $gold_coin*$goods_num;
        }else{
            $goodsInfo=Db::name("goods_spec")
                ->alias("gs")
                ->join("mm_goods g",'g.goods_id=gs.goods_id')
                ->join("mm_goods_info gn",'g.goods_id=gn.goods_id')
                ->field("gs.price,gs.coin_price,gn.delivery_type,gn.delivery_fee,gn.distribution_method")
                ->where(['gs.gs_id'=>$spec_id])
                ->find();
            $total_shipping_fee=0;
            $goods_num=$input['goods_num'];
            $total_score=$goodsInfo['price']*$goods_num;
            if($goodsInfo['distribution_method']!=2) {

                if($goodsInfo['delivery_type']==1) {
                    $total_shipping_fee+=$goodsInfo['delivery_fee'];
                }else {
                    $total_shipping_fee+=10; //第三方
                }
            }
            $total_coin=$goodsInfo['coin_price']*$goods_num;
         }
          returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);
    }


    /**
     * 更改地址计算运费
     */
    public function computeCartOrderFee($input){

        $cart_list=$input['cart_list'] ;
        $member_id=$input['member_id'] ;
        $ma_id=$input['ma_id'];
        $cart_list=explode(",",$cart_list);
        $cartList=Db::name('cart')->alias("c")
            ->where(['c.member_id'=>$member_id,"c.cart_id"=>['in',$cart_list],'c.source_type'=>$input['source_type']])
            ->column("c.d_method,c.d_type,c.spec_id,c.goods_id,c.goods_num","spec_id");
        $address=Db::name("member_address")->find($ma_id);
        if(empty($address)){
            returnJson(-2003,'请选择收货地址');
        }
        if( empty($address['m_name'])||empty($address['m_mobile'])||empty($address['province'])||empty($address['city'])||empty($address['county'])||empty($address['address_detail'])){
            returnJson(-2003,'收货地址信息不完整');
        }
        $province = $address['province'];
        $city = $address['city'];
        $area = $address['county'];
        $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
        $orderParam =[
            'address'=>[
                'consignee' => $address['m_name'],
                'phone' => $address['m_mobile'],
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'description' => $street,
            ],
        ];
        if(in_array($input['source_type'],[2,3])){//供应链
            $goodsArr=array_column($cartList,'goods_id');
            $goodsList=Db::name("choice_goods")
                ->where(['goods_id'=>['in', $goodsArr]])
                ->column('title','goods_id');
            $total_score=0;
            $total_shipping_fee=0;
            $total_coin=0;
            foreach ($cartList as $cart){
                $goods_id=$cart['goods_id'];
                $spec_id=$cart['spec_id'];
                $goodsInfo=$goodsList[$goods_id];
                $goods_num=$cart['goods_num'];
                $spec=$this->getGoodsSpec($goods_id, $spec_id,$goodsInfo);
                $stock=$spec['stock'];
                if($goods_num>$stock){
                    returnJson(-2003,'商品【'.$goodsInfo['title']."】库存不足");
                }
                if(empty($goodsInfo['is_free_shipping'])){//不包邮
                    $rst=$this->computeFee($spec_id,$goods_num,$orderParam);
                    $total_shipping_fee+=$rst['freight'];

                }else{
                    $total_shipping_fee+=0;
                }
                $gold_coin=0;
                $price=$spec['agreement_price'];

                //价格计算
                $orderPrice=$this->computePrice($goods_id,$input['source_type'],$spec['agreement_price']);
                extract($orderPrice);
                $total_score+= $price*$goods_num;
                $total_coin+= $gold_coin*$goods_num;
            }
        }else{
            $specList=array_column($cartList,'spec_id');
            $goodsList=Db::name("goods_spec")
                ->alias("gs")
                ->join("mm_goods g",'g.goods_id=gs.goods_id')
                ->join("mm_goods_info gn",'g.goods_id=gn.goods_id')
                ->field("gs.price,gs.coin_price,gn.delivery_type,gn.delivery_fee,gn.distribution_method")
                ->where(['gs.gs_id'=>['in',$specList]])
                ->select();
            $total_score=0;
            $total_shipping_fee=0;
            $total_coin=0;
           foreach ($goodsList as $item){
                $goods_num=$cartList[$item['spec_id']]['goods_num'];
                $total_score+=$item['price']*$goods_num;
                if($item['distribution_method']==2) {
                    $total_shipping_fee+=0;
                }else{
                    if($item['delivery_type']==1) {
                        $total_shipping_fee+=$item['delivery_fee'];
                    }else {
                        $total_shipping_fee+=10; //第三方
                    }
                }
                $total_coin+=$item['coin_price']*$goods_num;
           }

        }
        returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);
    }








}